/**
 * @author: dn-jinmin/dn-jinmin
 * @doc:
 */

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"
)

var url = "https://cn.apihz.cn/api/tianqi/tqyb.php?id=88888888&key=88888888&sheng=%s&place=%s"

func main() {
	citys := map[string]string{
		"四川": "绵阳",
		"湖南": "长沙",
		"北京": "北京",
	}
	ctx := context.Background()

	ch := make(chan *Response, 1)
	var wg sync.WaitGroup
	for sheng, place := range citys {
		wg.Add(1)
		go func(ctx context.Context, sheng, place string) {
			defer wg.Done()
			res, err := Request(sheng, place)
			if err != nil {
				log.Println(err)
			}
			ch <- res
		}(ctx, sheng, place)
	}

	go func() {
		wg.Wait()
		close(ch)
	}()

	for response := range ch {
		if response == nil {
			continue
		}
		fmt.Println(response.Place, " ", response.Weather1, " ", response.Weather2)
	}

	fmt.Println("程序结束")
}

func Request(sheng, place string) (*Response, error) {
	done := make(chan *Response)
	go func() {
		data, err := curl(fmt.Sprintf(url, sheng, place))
		if err != nil {
			done <- nil
			return
		}
		var res Response
		if err = json.Unmarshal(data, &res); err != nil {
			done <- nil
			return
		}
		done <- &res
	}()

	select {
	case res := <-done:
		return res, nil
	case <-time.After(time.Second):
		return nil, fmt.Errorf("request timeout")
	}

}

func curl(url string) ([]byte, error) {
	resp, err := http.Get(url)
	defer resp.Body.Close()

	responseBuffer := new(bytes.Buffer)
	_, err = responseBuffer.ReadFrom(resp.Body)
	if err != nil {
		return nil, err
	}

	return responseBuffer.Bytes(), nil
}
